<template>
  <div class="user-management">
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <h2>用户管理</h2>
        <div>
          <el-button type="primary" @click="showAddEmployeeDialog = true">添加员工</el-button>
          <el-button type="primary" @click="fetchUsers">刷新数据</el-button>
        </div>
      </div>
    </template>

      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/姓名/公司"
          style="width: 300px"
          clearable
          @clear="handleSearchClear"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="roleFilter" placeholder="角色筛选" clearable style="width: 200px">
          <el-option label="管理员" value="Admin" />
          <el-option label="员工" value="Employee" />
          <el-option label="客户" value="Customer" />
        </el-select>
      </div>

      <el-table
        :data="filteredUsers"
        style="width: 100%"
        border
        v-loading="loading"
        stripe
        highlight-current-row
      >
        <el-table-column prop="userId" label="ID" width="80" sortable />
        <el-table-column prop="username" label="登录账号" width="120" sortable />
        <el-table-column prop="fullName" label="姓名" width="120" sortable />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleLabel(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="companyName" label="公司名称" width="150" sortable />
        <el-table-column prop="email" label="邮箱" width="180" />

        <el-table-column prop="customerRegistrationStatus" label="注册状态" width="120">
          <template #default="scope">
            <el-tag
              v-if="scope.row.role === 'Customer'||'Admin'||'Employee'"
              :type="getStatusTagType(scope.row.customerRegistrationStatus)"
            >
              {{ getStatusLabel(scope.row.customerRegistrationStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="isActive" label="账号状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '正常' : '已冻结' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="270">
          <template #default="scope">
            <el-space>
              <template
                v-if="
                  scope.row.role === 'Customer' &&
                  scope.row.customerRegistrationStatus === 'PendingApproval'
                "
              >
                <el-button type="success" size="small" @click="approveCustomer(scope.row)">
                  批准
                </el-button>
                <el-button type="danger" size="small" @click="rejectCustomer(scope.row)">
                  拒绝
                </el-button>
              </template>

              <el-button
                :type="scope.row.isActive ? 'warning' : 'success'"
                size="small"
                @click="toggleUserStatus(scope.row)"
              >
                {{ scope.row.isActive ? '冻结' : '解冻' }}
              </el-button>
              <el-button 
                type="info" 
                size="small" 
                @click="resetPassword(scope.row)"
              >
                重置密码
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalUsers"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>

  <el-dialog v-model="showAddEmployeeDialog" title="添加新员工" width="500px">
    <el-form :model="employeeForm" :rules="rules" ref="employeeFormRef" label-width="100px">
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="employeeForm.username" style="width: 300px" />
      </el-form-item>
      <el-form-item label="姓名：" prop="fullName">
        <el-input v-model="employeeForm.fullName" style="width: 300px" />
      </el-form-item>
      <el-form-item label="密码：" prop="passwordHash">
        <el-input 
          v-model="employeeForm.passwordHash" 
          :type="showPassword ? 'text' : 'passwordHash'" 
          style="width: 300px"
        >
          <template #suffix>
            <el-icon @click="showPassword = !showPassword" style="cursor: pointer">
              <View v-if="showPassword" />
              <Hide v-else />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="employeeForm.email" style="width: 300px" />
      </el-form-item>
      <el-form-item label="联系电话：" prop="phone">
        <el-input v-model="employeeForm.phone" style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddEmployeeDialog = false">取消</el-button>
      <el-button type="primary" @click="submitEmployeeForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, View, Hide } from '@element-plus/icons-vue'

const users = ref([])
const filteredUsers = computed(() => {
  let filtered = users.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(
      (user) =>
        user.username.toLowerCase().includes(query) ||
        user.fullName.toLowerCase().includes(query) ||
        (user.companyName && user.companyName.toLowerCase().includes(query))
    )
  }

  // 角色过滤
  if (roleFilter.value) {
    filtered = filtered.filter((user) => user.role === roleFilter.value)
  }

  totalUsers.value = filtered.length

  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const searchQuery = ref('')
const roleFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const loading = ref(false)

const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/users')
    users.value = response.data
    totalUsers.value = response.data.length
  } catch (error) {
    console.error('Error fetching users:', error)
    ElMessage.error('获取用户数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearchClear = () => {
  searchQuery.value = ''
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 角色标签类型映射
const getRoleTagType = (role) => {
  const types = {
    Admin: 'danger',
    Employee: 'warning',
    Customer: 'primary',
  }
  return types[role] || 'info'
}

// 角色中文标签映射
const getRoleLabel = (role) => {
  const labels = {
    Admin: '管理员',
    Employee: '员工',
    Customer: '客户',
  }
  return labels[role] || role
}

// 状态标签类型映射
const getStatusTagType = (status) => {
  const types = {
    PendingApproval: 'warning',
    Approved: 'success',
    Rejected: 'danger',
  }
  return types[status] || 'info'
}

// 状态中文标签映射
const getStatusLabel = (status) => {
  const labels = {
    PendingApproval: '待审核',
    Approved: '已通过',
    Rejected: '已拒绝',
  }
  return labels[status] || status
}

// 其余方法保持不变
const approveCustomer = async (user) => {
  try {
    const response = await axios.put(`http://localhost:8080/api/users/approve/${user.userId}`)
    
    if (response.data) {
      ElMessage.success(`客户 "${user.username}" 已批准成功!`)
      await fetchUsers()
    } else {
      ElMessage.error(`批准客户 "${user.username}" 失败`)
    }
  } catch (error) {
    console.error('批准客户时出错:', error)
    ElMessage.error(error.response?.data?.message || '批准客户时发生错误')
  }
}

const rejectCustomer = async (user) => {
  try {
    const response = await axios.put(`http://localhost:8080/api/users/reject/${user.userId}`)
    
    if (response.data) {
      ElMessage.success(`客户 "${user.username}" 已拒绝成功`)
      await fetchUsers()
    } else {
      ElMessage.error(`拒绝客户 "${user.username}" 失败`)
    }
  } catch (error) {
    console.error('拒绝客户时出错:', error)
    ElMessage.error(error.response?.data?.message || '拒绝客户时发生错误')
  }
}

const resetPassword = (user) => {
  ElMessageBox.confirm(
    `确定要重置用户 ${user.username} 的密码为123456吗？`,
    '重置密码确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.put(`http://localhost:8080/api/users/reset-password/${user.userId}`)
      if (response.data) {
        ElMessage.success(`用户 ${user.username} 密码已重置为123456`)
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '密码重置失败')
    }
  }).catch(() => {
    ElMessage.info('已取消重置')
  })
}

const toggleUserStatus = async (user) => {
  try {
    const endpoint = user.isActive
      ? `http://localhost:8080/api/users/freeze/${user.userId}`
      : `http://localhost:8080/api/users/unfreeze/${user.userId}`

    const response = await axios.put(endpoint, {})

    if (response.data) {
      ElMessage.success(`用户 "${user.username}" ${!user.isActive ? '已解冻' : '已冻结'}`)
      await fetchUsers() // 重新获取最新数据
    } else {
      ElMessage.error(`更改用户 "${user.username}" 状态失败`)
    }
  } catch (error) {
    console.error('更改用户状态时出错:', error)
    ElMessage.error(error.response?.data?.message || '更改用户状态时发生错误')
  }
}

const showAddEmployeeDialog = ref(false)
const showPassword = ref(false)
const employeeForm = ref({
  username: '',
  fullName: '',
  passwordHash: '',
  email: '',
  phone: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const submitEmployeeForm = async () => {
  try {
    const response = await axios.post('http://localhost:8080/api/users/employees', employeeForm.value)
    if (response.data) {
      ElMessage.success('员工添加成功')
      showAddEmployeeDialog.value = false
      employeeForm.value = {
        username: '',
        fullName: '',
        passwordHash: '',
        email: '',
        phone: ''
      }
      await fetchUsers()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '添加员工失败')
  }
}

onMounted(fetchUsers)
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  align-items: center;
}

.el-tag {
  text-align: center;
  min-width: 60px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
}

:deep(.el-table__header-wrapper) th {
  background-color: #f5f7fa !important;
}

:deep(.el-table--striped) .el-table__row--striped {
  background-color: #fafafa;
}
</style>
